#include "unp.h"


static void sig_usr1(int signo);

mqd_t mqd;
void  *buff;
struct mq_attr attr;
struct sigevent sigev;

int main(int argc,char *argv[])
{
   int signo;
   sigset_t newmask;
   sigemptyset(&newmask);
   sigaddset(&newmask,SIGUSR1);
   sigprocmask(SIG_BLOCK,&newmask,NULL);

   mqd = mq_open(argv[1],O_RDONLY | O_NONBLOCK);
   if(mqd == -1)
     err_sys("mq_open error");
   if(mq_getattr(mqd,&attr) == -1)
     err_sys("mq_getattr error");
 
   buff = malloc(attr.mq_msgsize);

   //signal(SIGUSR1,sig_usr1);
   sigev.sigev_notify=SIGEV_SIGNAL;
   sigev.sigev_signo =SIGUSR1;
   if(mq_notify(mqd,&sigev) ==-1)
     err_sys("mq_notify error");

   for(;;){
     sigwait(&newmask,&signo);
     if(signo == SIGUSR1){
       ssize_t n;
       u_int32_t prio;
       printf("sig_usr1 begin\n");
       if(mq_notify(mqd,&sigev) ==-1)
         err_sys("mq_notify error");
       while((n=mq_receive(mqd,buff,attr.mq_msgsize,&prio)) !=-1){
         printf("SIGUSR1 received, read %ld bytes\n",(long)n);
       }
     }
   }
   exit(0);
}

static void sig_usr1(int signo){
   ssize_t n;
   u_int32_t prio;
   printf("sig_usr1 begin\n");
   if(mq_notify(mqd,&sigev) ==-1)
     err_sys("mq_notify error");
   while((n=mq_receive(mqd,buff,attr.mq_msgsize,&prio)) !=-1){
      printf("SIGUSR1 received, read %ld bytes\n",(long)n);
   }
   //if(n==-1 || n == 0)
      printf("SIGUSR1 received, no element %ld\n",(long)n);
   return;
}
